﻿using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Collections;
using System.Net.Mail;

namespace QuanLyNhanVien
{
    //public frmGiaoDienChinh frmGiaoDienChinh;

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// 
        /// 
        /// </summary>
        /// 

        public const int Server2ClientLoginOk = 1;
        public const int Server2ClientLoginFail = 2;
        public const int Server2ClientSendListOfUser = 3;
        public const int Server2ClientSendConnectionAlive = 4;
        public const int Server2ClientDataOk = 5;
        public const int Server2ClientDataNotOk = 6;
        public const int Server2ClientUpdateInsertDeleteDataOk = 7;
        public const int Server2ClientUpdateInsertDeleteDataFailed = 8;
        public const int Server2ClientReturnData = 9;
        public const int Server2ClientLogoutOk = 10;
        public const int Server2ClientSignedInOtherPlace = 11;
        public const int Server2ClientQueryFailed = 12;
        public const int Server2ClientSaveImageFailed = 13;
        public const int Server2ClientSaveImageOk = 14;
        public const int Server2ClientGetImageFailed = 15;
        public const int Server2ClientGetImageOk = 16;
        public const int Server2ClientStartTransactionOk = 17;
        public const int Server2ClientStartTransactionFailed = 18;
        public const int Server2ClientCommitTransactionOk = 19;
        public const int Server2ClientCommitTransactionFailed = 20;
        public const int Server2ClientRollbackTransactionOk = 21;
        public const int Server2ClientRollbackTransactionFailed = 22;
        public const int Server2ClientLogoutByTimeOut = 23;
        public const int Server2ClientReturnThongTinMoi = 24;
        public const int Server2ClientGetThongTinMoiFailed = 25;

        public const int Client2ServerLogin = 1;
        public const int Client2ServerSeeAllUser = 2;
        public const int Client2ServerUpdateInsertDeleteData = 3;
        public const int Client2ServerSendConnectionAlive = 4;
        public const int Client2ServerCheckData = 5;
        public const int Client2ServerQueryData = 6;
        public const int Client2ServerLogout = 7;
        public const int Client2ServerDataImage = 8;
        public const int Client2ServerGetDataImage = 9;
        public const int Client2ServerStartTransaction = 10;
        public const int Client2ServerCommitTransaction = 11;
        public const int Client2ServerRollbackTransaction = 12;
        public const int Client2ServerGetThongTinMoi = 13;


        public const int iNULLVALUE = -999999999;
        public static frmGiaoDienChinh afrmGiaoDienChinh;
        public static int[] aiIDDepart;
        public static string[] astrNameDepart;
        public static int giDepartCount;

        public static string gstrUserName;
        public static int giIDUser;
        public static int giIDDonVi;
        public static bool bDangNhap;
        public static int giQueryLength;

        public static Hashtable ghstbFunctions;

        [STAThread]

        static void Main()
        {
            // Create the thread object. This does not start the thread.
            SocketManager workerObject = new SocketManager();
            Thread workerThread = new Thread(workerObject.doManage);

            // Start the worker thread.
            workerThread.Start();
            Console.WriteLine("main thread: Starting worker thread...");

            // Loop until worker thread activates.
            while (!workerThread.IsAlive) ;

            // Create the thread object. This does not start the thread.
            SocketManager workerObjectSending = new SocketManager();
            Thread workerThreadSending = new Thread(workerObjectSending.doManageSending);

            // Start the worker thread.
            workerThreadSending.Start();
            Console.WriteLine("main thread: Starting worker thread sending...");

            // Loop until worker thread activates.
            while (!workerThreadSending.IsAlive) ;

            // Put the main thread to sleep for 1 millisecond to
            // allow the worker thread to do some work:

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //      Application.Run(new frmTinhTrangThucHien_Det());
            bDangNhap = false;
            afrmGiaoDienChinh = new frmGiaoDienChinh();
            Application.Run(afrmGiaoDienChinh);

            //      Application.Run(new frmKeHoachSanXuatHienTai());
            //      Application.Run(new frmGiaiDoan(1));
            //       Application.Run(new frmTaoMoiKeHoachSanXuat(new ArrayList()));

            // Request that the worker thread stop itself:
            workerObject.RequestStop();
            workerObjectSending.RequestStop();
            // Use the Join method to block the current thread 
            // until the object's thread terminates.
            workerThread.Join();
            Console.WriteLine("main thread: SocketManager Thread is terminated.");
            workerThreadSending.Join();
            Console.WriteLine("main thread: SocketManager Thread is terminated.");

        }

        public static int DBExecute(string iStrDBName, string strCommand) // strConmand co the la: insert, delete, update
        {
            int iPort = 0;
            IPEndPoint iep;
            byte[] abDBName;
            try
            {
                iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 18115);//117.6.133.202 
                if (frmDangNhap.gsckClient == null)
                {
                    frmDangNhap.gsckClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    frmDangNhap.gsckClient.Connect(iep);
                }

                Program.waitReceiveFlag(); 
                iPort = BitConverter.ToUInt16(SocketManager.gBRecvBuff, 0);
                frmDangNhap.gsckClient.Close();
                frmDangNhap.gsckClient = null;

                iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), iPort);
                if (frmDangNhap.gsckClient == null)
                {
                    frmDangNhap.gsckClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    frmDangNhap.gsckClient.Connect(iep);
                }

                abDBName = new byte[12 + Encoding.UTF8.GetBytes(iStrDBName).Length];

                //length
                BitConverter.GetBytes(8 + iStrDBName.Length).CopyTo(abDBName, 0);

                //isReadOnly
                BitConverter.GetBytes(0).CopyTo(abDBName, 4);

                //Reserved
                BitConverter.GetBytes(0).CopyTo(abDBName, 8);

                //Database Name
                Encoding.UTF8.GetBytes(iStrDBName).CopyTo(abDBName, 12);

                lock (frmDangNhap.sendingQueue)
                {
                    frmDangNhap.sendingQueue.Add(abDBName);
                }

            }
            catch
            {
                frmDangNhap.gsckClient = null;
                MessageBox.Show("Không thể kết nối đến server!");
                return -1;
            }

            Program.waitReceiveFlag(); 
            if (BitConverter.ToInt32(SocketManager.gBRecvBuff, 0) == 4 && BitConverter.ToInt32(SocketManager.gBRecvBuff, 4) == 0)//OK
            {
                //length
                BitConverter.GetBytes(8 + strCommand.Length).CopyTo(abDBName, 0);

                //Command of execution
                BitConverter.GetBytes(2).CopyTo(abDBName, 4);

                //Query to execute
                Encoding.UTF8.GetBytes(strCommand).CopyTo(abDBName, 8);

                //send package to server
                lock (frmDangNhap.sendingQueue)
                {
                    frmDangNhap.sendingQueue.Add(abDBName);
                }
                Program.waitReceiveFlag();

                if (BitConverter.ToInt32(SocketManager.gBRecvBuff, 0) == 4 && BitConverter.ToInt32(SocketManager.gBRecvBuff, 4) == 0)//OK
                {
                    frmDangNhap.gsckClient.Close();
                    frmDangNhap.gsckClient = null;
                    return 0;
                }
                else
                {
                    frmDangNhap.gsckClient.Close();
                    frmDangNhap.gsckClient = null;
                    MessageBox.Show("Lỗi thực thi câu SQL");
                    return -1;

                }
            }
            else
            {
                frmDangNhap.gsckClient.Close();
                frmDangNhap.gsckClient = null;
                MessageBox.Show("Lỗi Database name");
                return -1;
            }

        }

        public static int DBInsert(string iStrDBName, string strQuery, string strTable, string strIDField)
        {
            int iPort = 0;
            IPEndPoint iep;
            byte[] abDBName;
            try
            {
                iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 18115);//117.6.133.202 
                if (frmDangNhap.gsckClient == null)
                {
                    frmDangNhap.gsckClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    frmDangNhap.gsckClient.Connect(iep);
                }

                Program.waitReceiveFlag(); 

                iPort = BitConverter.ToUInt16(SocketManager.gBRecvBuff, 0);
                frmDangNhap.gsckClient.Close();
                frmDangNhap.gsckClient = null;

                iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), iPort);
                if (frmDangNhap.gsckClient == null)
                {
                    frmDangNhap.gsckClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    frmDangNhap.gsckClient.Connect(iep);
                }

                abDBName = new byte[12 + Encoding.UTF8.GetBytes(iStrDBName).Length];

                //length
                BitConverter.GetBytes(8 + iStrDBName.Length).CopyTo(abDBName, 0);

                //isReadOnly
                BitConverter.GetBytes(0).CopyTo(abDBName, 4);

                //Reserved
                BitConverter.GetBytes(0).CopyTo(abDBName, 8);

                //Database Name
                Encoding.UTF8.GetBytes(iStrDBName).CopyTo(abDBName, 12);

                lock (frmDangNhap.sendingQueue)
                {
                    frmDangNhap.sendingQueue.Add(abDBName);
                }

            }
            catch
            {
                frmDangNhap.gsckClient = null;
                MessageBox.Show("Không thể kết nối đến server!");
                return -1;
            }

            Program.waitReceiveFlag(); 

            if (BitConverter.ToInt32(SocketManager.gBRecvBuff, 0) == 4 && BitConverter.ToInt32(SocketManager.gBRecvBuff, 4) != -1)//OK
            {
                //length
                BitConverter.GetBytes(8 + strQuery.Length + strTable.Length + strIDField.Length).CopyTo(abDBName, 0);

                //Command of INSERT
                BitConverter.GetBytes(4).CopyTo(abDBName, 4);

                //Insert query
                Encoding.UTF8.GetBytes(strQuery).CopyTo(abDBName, 8);

                //Table name
                Encoding.UTF8.GetBytes(strTable).CopyTo(abDBName, 8 + strQuery.Length);

                //ID-field name
                Encoding.UTF8.GetBytes(strIDField).CopyTo(abDBName, 8 + strQuery.Length + strTable.Length);

                //send insert command package to server
                lock (frmDangNhap.sendingQueue)
                {
                    frmDangNhap.sendingQueue.Add(abDBName);
                }

                Program.waitReceiveFlag(); 

                if (BitConverter.ToInt32(SocketManager.gBRecvBuff, 0) == 4 && BitConverter.ToInt32(SocketManager.gBRecvBuff, 4) != -1)//OK
                {
                    frmDangNhap.gsckClient.Close();
                    frmDangNhap.gsckClient = null;
                    return (BitConverter.ToInt32(SocketManager.gBRecvBuff, 4));
                }
                else
                {
                    frmDangNhap.gsckClient.Close();
                    frmDangNhap.gsckClient = null;
                    MessageBox.Show("Lỗi thực thi câu INSERT dữ liệu");
                    return -1;

                }
            }
            else
            {
                MessageBox.Show("Lỗi trong xảy ra trong quá trình thực thi câu SQL");
                frmDangNhap.gsckClient.Close();
                frmDangNhap.gsckClient = null;
                return -1;
            }
        }


        public static byte[] DBQuery(string iStrDBName, string strQuery)
        {
            int iPort = 0;
            int iLen = 0;
            IPEndPoint iep, iep1;
            byte[] abDBName;
            byte[] abDBName1;
            byte[] abReturn;
            string strTemp;
            try
            {
                iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 18115);//117.6.133.202 
                if (frmDangNhap.gsckClient == null)
                {
                    frmDangNhap.gsckClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    frmDangNhap.gsckClient.Connect(iep);
                }

                Program.waitReceiveFlag(); 

                iPort = BitConverter.ToUInt16(SocketManager.gBRecvBuff, 0);
                frmDangNhap.gsckClient.Shutdown(SocketShutdown.Both);
                frmDangNhap.gsckClient.Disconnect(false);
                frmDangNhap.gsckClient.Close();
                frmDangNhap.gsckClient = null;


                iep1 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), iPort);
                if (frmDangNhap.gsckClient == null)
                {
                    frmDangNhap.gsckClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    frmDangNhap.gsckClient.Connect(iep1);
                }
                //frmDangNhap.gsckClient.Connect(iep1);
                
                abDBName = new byte[12 + Encoding.UTF8.GetBytes(iStrDBName).Length];

                //length
                BitConverter.GetBytes(8 + iStrDBName.Length).CopyTo(abDBName, 0);

                //isReadOnly
                BitConverter.GetBytes(0).CopyTo(abDBName, 4);

                //Reserved
                BitConverter.GetBytes(0).CopyTo(abDBName, 8);

                //Database Name
                Encoding.UTF8.GetBytes(iStrDBName).CopyTo(abDBName, 12);

                lock (frmDangNhap.sendingQueue)
                {
                    frmDangNhap.sendingQueue.Add(abDBName);
                }

            }
            catch
            {
                frmDangNhap.gsckClient = null;
                MessageBox.Show("Không thể kết nối đến server!");
                return null;
            }

            Program.waitReceiveFlag(); 

            if (BitConverter.ToInt32(SocketManager.gBRecvBuff, 0) == 4 && BitConverter.ToInt32(SocketManager.gBRecvBuff, 4) == 0)//OK
            {
                abDBName1 = new byte[8 + Encoding.UTF8.GetBytes(strQuery).Length];
                //length
                BitConverter.GetBytes(4 + strQuery.Length).CopyTo(abDBName1, 0);

                //Command of SELECT
                BitConverter.GetBytes(3).CopyTo(abDBName1, 4);

                //Query to execute
                Encoding.UTF8.GetBytes(strQuery).CopyTo(abDBName1, 8);

                //send package to server
                lock (frmDangNhap.sendingQueue)
                {
                    frmDangNhap.sendingQueue.Add(abDBName1);
                }
                Program.waitReceiveFlag(); 

                if (BitConverter.ToInt32(SocketManager.gBRecvBuff, 4) == 0)//OK
                {
                    iLen = BitConverter.ToInt32(SocketManager.gBRecvBuff, 0);
                    abReturn = new byte[iLen - 4];
                    strTemp = Encoding.UTF8.GetString(SocketManager.gBRecvBuff, 8, iLen - 4);
                    Encoding.UTF8.GetBytes(strTemp).CopyTo(abReturn, 0);

                    frmDangNhap.gsckClient.Shutdown(SocketShutdown.Both);
                    frmDangNhap.gsckClient.Disconnect(false);
                    frmDangNhap.gsckClient.Close();
                    frmDangNhap.gsckClient = null;

                    return abReturn;
                }
                else
                {
                    frmDangNhap.gsckClient.Close();
                    frmDangNhap.gsckClient = null;
                    MessageBox.Show("Lỗi thực thi câu SELECT Query");
                    return null;

                }
            }
            else
            {
                frmDangNhap.gsckClient.Close();
                frmDangNhap.gsckClient = null;
                MessageBox.Show("Lỗi Database name không đúng!");
                return null;
            }
        }

        public static bool startTransaction()
        {
            SocketManager.gbSocketRecvMutex = true;

            try
            {
                byte[] abQue = new byte[8];
                //length
                BitConverter.GetBytes(4).CopyTo(abQue, 0);

                //command
                BitConverter.GetBytes(Program.Client2ServerStartTransaction).CopyTo(abQue, 4);
                lock (frmDangNhap.sendingQueue)
                {

                    frmDangNhap.sendingQueue.Add(abQue);
                }
                waitReceiveFlag();

                byte[] abRecFunctions = new byte[10000];
                abRecFunctions.Initialize();

                SocketManager.gBRecvBuff.CopyTo(abRecFunctions, 0);

                int iLen = BitConverter.ToInt32(abRecFunctions, 0);
                int iCommand = BitConverter.ToInt32(abRecFunctions, 4);
                if (iCommand == Server2ClientStartTransactionOk)
                {
                    SocketManager.gbSocketRecvMutex = false;
                    return true;
                }
                else
                {
                    SocketManager.gbSocketRecvMutex = false;
                    return false;
                }
            }
            catch
            {
                SocketManager.gbSocketRecvMutex = false;
               // returnError(Program.giIDDonVi, Program.giIDUser, "Khong co", "startTransaction", "Program");
                return false;
            }
        }

        public static bool commitTransaction()
        {
            SocketManager.gbSocketRecvMutex = true;

            try
            {
                byte[] abQue = new byte[8];
                //length
                BitConverter.GetBytes(4).CopyTo(abQue, 0);

                //command
                BitConverter.GetBytes(Program.Client2ServerCommitTransaction).CopyTo(abQue, 4);
                lock (frmDangNhap.sendingQueue)
                {
                    frmDangNhap.sendingQueue.Add(abQue);
                }
                waitReceiveFlag();
                byte[] abRecFunctions = new byte[10000];
                abRecFunctions.Initialize();

                SocketManager.gBRecvBuff.CopyTo(abRecFunctions, 0);

                int iLen = BitConverter.ToInt32(abRecFunctions, 0);
                int iCommand = BitConverter.ToInt32(abRecFunctions, 4);
                if (iCommand == Server2ClientCommitTransactionOk)
                {
                    SocketManager.gbSocketRecvMutex = false;
                    return true;
                }
                else
                {
                    SocketManager.gbSocketRecvMutex = false;
                    return false;
                }
            }
            catch
            {
                SocketManager.gbSocketRecvMutex = false;
               // returnError(Program.giIDDonVi, Program.giIDUser, "Khong co", "commitTransaction", "Program");
                return false;
            }
        }

        public static bool rollbackTransaction()
        {
            SocketManager.gbSocketRecvMutex = true;

            try
            {
                byte[] abQue = new byte[8];
                //length
                BitConverter.GetBytes(4).CopyTo(abQue, 0);

                //command
                BitConverter.GetBytes(Program.Client2ServerRollbackTransaction).CopyTo(abQue, 4);
                lock (frmDangNhap.sendingQueue)
                {
                    frmDangNhap.sendingQueue.Add(abQue);
                }
                waitReceiveFlag();
                byte[] abRecFunctions = new byte[10000];
                abRecFunctions.Initialize();
                SocketManager.gBRecvBuff.CopyTo(abRecFunctions, 0);

                int iLen = BitConverter.ToInt32(abRecFunctions, 0);
                int iCommand = BitConverter.ToInt32(abRecFunctions, 4);
                if (iCommand == Server2ClientRollbackTransactionOk)
                {
                    SocketManager.gbSocketRecvMutex = false;
                    return true;
                }
                else
                {
                    SocketManager.gbSocketRecvMutex = false;
                    return false;
                }
            }
            catch
            {
                SocketManager.gbSocketRecvMutex = false;
               // returnError(Program.giIDDonVi, Program.giIDUser, "Khong co", "rollbackTransaction", "Program");
                return false;
            }
        }

        public static int cheIntIsNull(int iNum)
        {
            if (iNum == iNULLVALUE)
            {
                iNum = 0;
            }
            return iNum;
        }

        public static Double cheDoubleIsNull(Double dNum)
        {
            if (dNum == iNULLVALUE)
            {
                dNum = 0;
            }
            return dNum;
        }

        public static void waitReceiveFlag()
        {
            Boolean bValue;
            lock (frmDangNhap.gReceivedFlag)
            {
                frmDangNhap.gReceivedFlag = false;
                bValue = (Boolean)frmDangNhap.gReceivedFlag;
                Console.WriteLine("assign frmDangNhap.gReceivedFlag == false+++++++++");
            }

            while (!bValue)
            {
                lock (frmDangNhap.gReceivedFlag)
                {
                    bValue = (Boolean)frmDangNhap.gReceivedFlag;
                }
                Thread.Sleep(2);
            }
        }

        public static void assignReceiveFlag()
        {
            lock (frmDangNhap.gReceivedFlag)
            {
                frmDangNhap.gReceivedFlag = true;
                Console.WriteLine("assign frmDangNhap.gReceivedFlag == true+++++++++");
                //Thread.Sleep(2);
            }
        }

     }




    public class SocketManager
    {
        public const int Server2ClientLoginOk = 1;
        public const int Server2ClientLoginFail = 2;
        public const int Server2ClientSendListOfUser = 3;
        public const int Server2ClientSendConnectionAlive = 4;
        public const int Server2ClientDataOk = 5;
        public const int Server2ClientDataNotOk = 6;
        public const int Server2ClientUpdateInsertDeleteDataOk = 7;
        public const int Server2ClientUpdateInsertDeleteDataFailed = 8;
        public const int Server2ClientReturnData = 9;
        public const int Server2ClientLogoutOk = 10;
        public const int Server2ClientSignedInOtherPlace = 11;
        public const int Server2ClientQueryFailed = 12;
        public const int Server2ClientSaveImageFailed = 13;
        public const int Server2ClientSaveImageOk = 14;
        public const int Server2ClientGetImageFailed = 15;
        public const int Server2ClientGetImageOk = 16;
        public const int Server2ClientStartTransactionOk = 17;
        public const int Server2ClientStartTransactionFailed = 18;
        public const int Server2ClientCommitTransactionOk = 19;
        public const int Server2ClientCommitTransactionFailed = 20;
        public const int Server2ClientRollbackTransactionOk = 21;
        public const int Server2ClientRollbackTransactionFailed = 22;
        public const int Server2ClientLogoutByTimeOut = 23;
        public const int Server2ClientReturnThongTinMoi = 24;
        public const int Server2ClientGetThongTinMoiFailed = 25;

        public static long glSendTimeCounter;
        public static long glRecvTimeCounter;
        public static bool gbSocketRecvMutex = false;

        public static Byte[] gBRecvBuff;
        public static Byte[] gBImageBuff;
        public static Byte[] gBGetTTMoiBuff;
        private volatile bool _shouldStop;
        private volatile bool _shouldStopSending;
        object obj = new object();
        // This method will be called when the thread is started.
        public void doManage()
        {
            bool bValue = true;
            //glRecvTimeCounter = glSendTimeCounter = DateTime.Now.Ticks;

            while (!_shouldStop)
            {
               
                if (frmDangNhap.gsckClient != null && frmDangNhap.gsckClient.Connected)
                {

                    while ((Boolean)frmDangNhap.gReceivedFlag || !frmDangNhap.gsckClient.Connected)
                    {
                        Thread.Sleep(2);
                    }
                    if (frmDangNhap.gsckClient.Available >= 2)
                    {
                        Byte[] bRecData0 = new Byte[10000];

                        int iNumRecv = frmDangNhap.gsckClient.Receive(bRecData0, 10000, System.Net.Sockets.SocketFlags.None);

                        Console.WriteLine("da nhan xong du lieu tu server  ");
                        gBRecvBuff = new Byte[10000];
                        bRecData0.CopyTo(gBRecvBuff, 0);
                        Program.assignReceiveFlag();
                    }
                    else
                    {
                        Thread.Sleep(10);
                    }
                }
                else
                {
                    Thread.Sleep(10);
                }
            }
        }

        public void RequestStop()
        {
            _shouldStop = true;
            _shouldStopSending = true;
        }


        public void doManageSending()
        {
            glRecvTimeCounter = glSendTimeCounter = DateTime.Now.Ticks;

            while (!_shouldStopSending)
            {
                if (frmDangNhap.gsckClient != null && frmDangNhap.gsckClient.Connected)
                {
                    if (DateTime.Now.Ticks - glSendTimeCounter >= (frmDangNhap.glTickPerSecond * frmDangNhap.glConnectionAlivePeriod))
                    {
                        glSendTimeCounter = DateTime.Now.Ticks;
                        try
                        {
                            Console.WriteLine("checking a package {0}", frmDangNhap.sendingQueue.Count);
                            
                        }
                        catch
                        {
                            MessageBox.Show("Không thể liên lạc với Server");
                            Program.afrmGiaoDienChinh.frmDangNhap.Delete();
                            Program.afrmGiaoDienChinh.loadGiaoDienDangNhap();
                        }
                    }
                    else
                    {
                        Thread.Sleep(10);
                    }
                    int iCount = 0;
                    lock (frmDangNhap.sendingQueue)
                    {
                        iCount = frmDangNhap.sendingQueue.Count;
                    }

                    if (iCount > 0)
                    {
                        Byte[] bSend;
                        lock (frmDangNhap.sendingQueue)
                        {
                            bSend = new Byte[frmDangNhap.sendingQueue.ElementAt(0).Length];
                            frmDangNhap.sendingQueue.ElementAt(0).CopyTo(bSend, 0);
                            frmDangNhap.sendingQueue.RemoveAt(0);
                        }

                        lock (frmDangNhap.gsckClient)
                        {
                            frmDangNhap.gsckClient.Send(bSend);
                        }
                        glSendTimeCounter = DateTime.Now.Ticks;
                        Console.WriteLine("sending a package");
                    }
                    else
                    {
                        Thread.Sleep(10);
                    }
                }
            }

            Console.WriteLine("quit a package");
        }


        /*
        public void loadGiaoDienDangNhap()
        {
            Program.afrmGiaoDienChinh.frmDangNhap = new frmDangNhap(Program.afrmGiaoDienChinh.pnlChinh, Program.afrmGiaoDienChinh);
            Program.afrmGiaoDienChinh.frmDangNhap.TopLevel = false;
            Program.afrmGiaoDienChinh.frmDangNhap.FormBorderStyle = FormBorderStyle.None;
            Program.afrmGiaoDienChinh.frmDangNhap.Dock = DockStyle.Fill;
            SetControlPropertyValue(Program.afrmGiaoDienChinh.pnlChinh, "controls", Program.afrmGiaoDienChinh.frmDangNhap);
            //pnlChinh.Controls.Add(frmDangNhap);
            Program.afrmGiaoDienChinh.frmDangNhap.Show();
        }

        delegate void SetControlValueCallback(Control oControl, string propName, object propValue);
        private void SetControlPropertyValue(Control oControl, string propName, object propValue)
        {
            if (oControl.InvokeRequired)
            {
                SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
                oControl.Invoke(d, new object[] { oControl, propName, propValue });
            }
            else
            {
                Type t = oControl.GetType();
                PropertyInfo[] props = t.GetProperties();
                foreach (PropertyInfo p in props)
                {
                    if (p.Name.ToUpper() == propName.ToUpper())
                    {
                        p.SetValue(oControl, propValue, null);
                    }
                }
            }
        }
        */
        // Volatile is used as hint to the compiler that this data
        // member will be accessed by multiple threads.

    }

}
